# encoding=utf-8

# ---------------------------------------------------------------------------------------------------------
#
#  按章节(二级标题)拆分markdown，并生成相应目录及列表
#
# ---------------------------------------------------------------------------------------------------------

import logging
from os import remove, rename
import sys

import config

# 以二级标题为文档章节拆分标志
CONST_SPLIT_CHAPTER_FLAG = '## '


MAIN_SCRIPT_TEMPLATE = '''
<script>
	const documents = [
$DOCUMENTS$
	];

    setTimeout(function() {
		documents.forEach(function(doc) {
			ul = document.querySelector('.doc-list');
			if (!ul) {return;}
			li = document.createElement('li');
			li.className = 'doc-item';
			ul.appendChild(li);

			a = document.createElement('a');
			a.href = '#/' + doc.id + '/';
			li.appendChild(a);

			docBox = document.createElement('div');
			docBox.className = 'doc-box';
			a.appendChild(docBox);

			docTitle = document.createElement('span');
			docTitle.className = 'doc-title';
			docTitle.innerText = 'DOCUMENT';
			docBox.appendChild(docTitle);

			docBg = document.createElement('div');
			docBg.className = 'doc-bg';
			docBox.appendChild(docBg);

			docBgName = document.createElement('span');
			docBgName.innerText = doc.name;
			docBg.appendChild(docBgName);

			docName = document.createElement('span');
			docName.className = 'doc-name';
			docName.innerText = doc.name;
			a.appendChild(docName);
		});
	}, 0);
</script>
'''


class Markdown(object):
    '''文档信息
    '''

    def __init__(self) -> None:
        super().__init__()

        self.name = ''
        self.full_name = ''
        self.document_id = ''
        self.standalone = True
        self.chapters = []
        # 冗余存放
        self.markdown_path = ''
        #
        self.is_reference = False

    def context_path(self):
        '''返回markdown文档根路径
        '''
        return self.markdown_path + self.document_id + '/'

    def full_path(self):
        '''返回markdown文档全路径
        '''
        return self.context_path() + self.full_name

    def sidebar_path(self):
        '''返回markdown目录路径
        '''
        return self.context_path() + config.SIDEBAR_NAME

    def readme_path(self):
        '''返回markdown主页路径
        '''
        return self.context_path() + config.HOME_PAGE_NAME

    def link_prefix(self):
        '''通过判断是否手册文档，决定是否返回链接前缀
        '''
        return config.REFERENCE_LINK_PREFIX if self.is_reference else ''


class Handler(object):
    '''markdown 处理器
    '''

    def __init__(self, base_path, is_reference, changed_documents, all_documents) -> None:
        super().__init__()

        if base_path is None or len(base_path) == 0:
            logging.error('文档处理基础地址不能为空，程序退出')
            sys.exit()

        # markdown 目录
        self._markdown_path = base_path + 'markdown/'
        # 是否引用文档目录
        self._is_reference = is_reference

        # 需要处理的 markdown 文件数组
        self._markdowns = []

        # 所有 document
        self._all_documents = all_documents

        # 创建 markdown 对象
        for d in changed_documents:
            md = Markdown()
            md.name = d.name
            md.full_name = d.name + '.md'
            md.document_id = d.id
            md.markdown_path = self._markdown_path
            md.is_reference = self._is_reference

            self._markdowns.append(md)

    def _split_chapter(self, markdown):
        '''拆分文档
        '''

        logging.info('拆分文档 [%s] [%s]', markdown.document_id, markdown.name)
        with open(markdown.full_path(), mode='r', encoding='utf-8') as r:
            temp_title = ''
            temp_content = ''
            while True:
                line = r.readline()
                if not line:
                    break

                if line.startswith(CONST_SPLIT_CHAPTER_FLAG):
                    self._create_single_chapter(markdown, temp_title, temp_content)
                    temp_title = line[2:].strip()
                    # 清空临时内容
                    temp_content = ''
                elif line.strip() == '**':
                    # 去掉分页符
                    continue
                else:
                    temp_content = temp_content + line

            # 处理最后章节
            self._create_single_chapter(markdown, temp_title, temp_content)

    def _create_single_chapter(self, markdown, title, content):
        '''创建单章节文件
        '''

        if not title or len(title) == 0:
            return

        # 处理掉名称中的空格
        title = self._rename_title(title)
        chapter_path = markdown.context_path() + self._rename_title(title) + '.md'
        logging.debug('创建章节文件 %s', chapter_path)

        with open(chapter_path, mode='w', encoding='utf-8') as f:
            f.writelines(content)

    def _rename_title(self, title):
        '''替换掉文件名中的空格
        '''
        return title.replace(' ', '_').strip('*')

    def _create_bar(self, markdown):
        '''生成 readme.md 和 _sidebar.md
        '''
        # 读取标题
        titles = []
        logging.debug('读取标题 %s', markdown.full_path())
        with open(markdown.full_path(), mode='r', encoding='utf-8') as r:
            while True:
                line = r.readline()
                if not line:
                    break
                if line.startswith(CONST_SPLIT_CHAPTER_FLAG):
                    titles.append(line[2:].strip())

        # 将标题写入 sidebar
        text = '- [{}]({}{}/{}.md)\n'
        logging.debug('写标题到README %s', markdown.sidebar_path())
        with open(markdown.sidebar_path(), mode='w', encoding='utf-8') as f:
            for t in titles:
                f.writelines(text.format(t, markdown.link_prefix(), markdown.document_id, self._rename_title(t)))

        # 将标题写入 README
        # text = '- [{}]({}/{}.md)\n'
        logging.debug('写标题到README %s', markdown.readme_path())
        with open(markdown.readme_path(), mode='w', encoding='utf-8') as f:
            # 写上标题
            f.writelines('# ' + markdown.name + '\n')
            for t in titles:
                f.writelines(text.format(t, markdown.link_prefix(), markdown.document_id, self._rename_title(t)))

    def _remove_origin(self, markdown):
        '''删除原始markdown
        '''
        logging.debug('清理原始文档 %s', markdown.full_path())
        remove(markdown.full_path())

    def _standalone(self, markdown):
        '''处理不需要拆分的文档
        '''
        logging.info('处理单文档 [%s] [%s]', markdown.document_id, markdown.name)
        # 创建空目录文件
        open(markdown.sidebar_path(), 'a').close()

        # 重命名文档即可
        rename(markdown.full_path(), markdown.readme_path())

    def _prepare(self, markdown):
        '''预处理一下文档
        '''

        with open(markdown.full_path(), mode='r', encoding='utf-8') as r:
            while True:
                line = r.readline()
                if not line:
                    break

                # 只要有二级标题，就拆分文档
                if line.startswith(CONST_SPLIT_CHAPTER_FLAG):
                    markdown.standalone = False
                    break

    def _create_main_table(self):
        '''生成主目录和主页面列表
        '''

        # 生成主目录 _sidebar.md
        text = ''
        for doc in self._all_documents:
            text = '{}<!-- {} -->\n'.format(text, doc.name)

            lines = []
            with open(self._markdown_path + doc.id + '/' + config.SIDEBAR_NAME, mode='r', encoding='utf-8') as f:
                lines = f.readlines()

            for line in lines:
                text += line

            text += '\n'
            pass

        with open(self._markdown_path + config.SIDEBAR_NAME, mode='w', encoding='utf-8') as f:
            f.writelines(text)

        text = ''
        # 手册文档，填充README模板
        if not self._is_reference:
            for doc in self._all_documents:
                text = '{}{{ id: {}, name: \'{}\', version: {}, timestamp: {} }},\n'.format(
                    text, doc.id, doc.name, doc.version, doc.last_publish)

            text = MAIN_SCRIPT_TEMPLATE.replace('$DOCUMENTS$', text)

        # 生成主页面列表 README.md
        with open(self._markdown_path + config.HOME_PAGE_NAME, mode='w', encoding='utf-8') as f:
            f.writelines(text)

    def handle(self):
        '''负责拆分文档及目录处理
        '''

        print('-------------------------------------------------------------------------------------------------------')

        logging.info('准备拆分文档(%s) %s', len(self._markdowns), self._markdown_path)

        for md in self._markdowns:
            # 预处理
            self._prepare(md)

            # 检查文档是否需要拆分
            if md.standalone:
                self._standalone(md)
            else:
                self._split_chapter(md)
                self._create_bar(md)
                self._remove_origin(md)

        if len(self._markdowns) > 0:
            # 生成主目录及主页面列表
            self._create_main_table()

        logging.info('文档拆分处理完毕')

        return self._markdowns
